﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BudgetMealsModels.Entities;
using BudgetMealsModels.Abstract;
using System.Data.SqlClient;
using System.Data.Entity.Validation;

namespace BudgetMealsModels.Concrete
{
    public class EFDbUserRepository : IUserRepository
    {
        private EFDbContext _context = EFDbContext.Context;

        public IQueryable<User> Users
        {
            get 
            {
                return _context.Users.Include("Recipes").Include("Meals").Include("Meals.Appetizer").Include("Meals.MainCourse").Include("Meals.Dessert"); 
            }
        }

        public int Edit(User user)
        {
            User check = _context.Users.FirstOrDefault(u => u.UserID == user.UserID);
            int idChanged = user.UserID;
            if (user.UserID == 0)
            {
                _context.Users.Add(user);
                try
                {
                    _context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                }
                idChanged = _context.Users.FirstOrDefault(x => x.UserName == user.UserName).UserID;
            }
            else
            {
                _context.Entry(_context.Users.SingleOrDefault(i => i.UserID == user.UserID)).CurrentValues.SetValues(user);
            }
            _context.SaveChanges();
            return idChanged;
        }

        public void Delete(User user)
        {
            if (user != null)
                _context.Users.Remove(user);
            _context.SaveChanges();
        }
    }
}
